
import { changeLoading } from "./loading";

function createScript (url) {
  return new Promise( (resolve, reject) => {
    const script = document.createElement('script');
    script.src = url
    script.onload = () => resolve(url);
    script.onerror = () => reject(new Error(`Script load error: ${url}`));  // 失败时 reject
    console.log(url, 'url----');
    const first = document.getElementsByTagName('script')[0]
    console.log(first, 'first----');
    
    first.parentNode.insertBefore(script, first)
  })
}
async function createCss(url) {
  const res = await fetch(url);
  const cssText = await res.text();
  const style = document.createElement('style')
  style.innerHTML = cssText;
  document.body.appendChild(style);
}

// async function loadApp (urls, name) {
//   // await Promise.all(urls.map( url => createScript(url)))
//   await createScript(urls[0])
//   await createScript(urls[1])
//   changeLoading(false)
//   return window[name]
// }
async function loadApp(urls, name, cssList) {
  try {
    for (const url of urls) {
      await createScript(url);
      console.log(`Loaded script: ${url}`);
    }
    if (cssList && cssList.length) {
      await createCss(cssList[0])
    }
    if (!window[name]) {
      throw new Error(`Application ${name} is not mounted to window after loading scripts.`);
    }

    console.log(`Application ${name} successfully loaded.`);
    changeLoading(false)
    return window[name];
  } catch (error) {
    console.error(`Error loading application ${name}:`, error);
    throw error;
  }
}


export const subNavList = [
  {
    name: 'react15',
    app: loadApp([ // 通过次函数获取到子应用的所有资源 js css
      'http://localhost:9002/react15.js',
    ], 'react15', [
      'http://localhost:9002/path.css'
    ]),
    activeWhen: location => location.pathname.startsWith('/react15'),
    customProps: {},
  },
  {
    name: 'react16',
    app: loadApp([
      'http://localhost:9003/react16.js',
    ], 'react16', [
      'http://localhost:9003/path.css'
    ]),
    activeWhen: location => location.pathname.startsWith('/react16'),
    customProps: {},
  },
  {
    name: 'vue2',
    app: loadApp([
      'http://localhost:9004/static/js/chunk-vendors.js',
      'http://localhost:9004/static/js/app.js'
    ], 'vue2'),
    activeWhen: location => location.pathname.startsWith('/vue2'),
    customProps: {},
  },
  {
    name: 'vue3',
    app: () => loadApp([
      'http://localhost:9005/static/js/chunk-vendors.js',
      'http://localhost:9005/static/js/app.js'
    ], 'vue3'),
    activeWhen: location => location.pathname.startsWith('/vue3'),
    customProps: {},
  },
]